package chendu.service;

import chendu.entity.BuyerAddress;
import chendu.form.AddressForm;
import chendu.mapper.AddressMapper;
import chendu.vo.AddressVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;



@Service

public class AddressService {

    @Autowired(required = false)
    private AddressMapper addressMapper;

    public List<AddressVO> findAll() {
        /**
         * findAll方法首先将sql查询到的数据分装到BuyerAddress的集合中返回
         * 并遍历封装到AddressVO中进行返回
         * */
        List<BuyerAddress> buyerAddressList=addressMapper.findAll();
        List<AddressVO> addressVOList= new ArrayList<>();

        for (BuyerAddress buyerAddress: buyerAddressList) {
            AddressVO addressVO = new AddressVO();
            addressVO.setId(buyerAddress.getAddressId());
            addressVO.setAreaCode(buyerAddress.getAreaCode());
            addressVO.setName(buyerAddress.getBuyerName());
            addressVO.setTel(buyerAddress.getBuyerPhone());
            addressVO.setAddress(buyerAddress.getBuyerAddress());
            addressVOList.add(addressVO);
        }
        //返回list对象
        return addressVOList;
    }
    /**
     * 通过前端AddressForm中获取id值，并进行匹配，
     * 对查询到的对象进行更新信息设置
     * */

    public void saveOrUpdate(AddressForm addressForm) {
        BuyerAddress buyerAddress;
        //获取id值
        Integer id = addressForm.getId();
        //判断对象id是否存在，存在就个更新，不存在就新增


        if(id == null){
            buyerAddress = new BuyerAddress();
        } else {
           buyerAddress = addressMapper.findById(id);
        }
        //将对象信息进行更新
         buyerAddress.setBuyerName(addressForm.getName());
        buyerAddress.setBuyerPhone(addressForm.getTel());
        //创建StringBuffer对象，对用户城市，区域，详细地址进行拼接
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append(addressForm.getProvince())
                .append(addressForm.getCity())
                .append(addressForm.getCounty())
                .append(addressForm.getAddressDetail());
        //将stringBuffer更新至封装实体对象中
        buyerAddress.setBuyerAddress(stringBuffer.toString());
        buyerAddress.setAreaCode(addressForm.getAreaCode());
        //增加if判断id为空执行新增语句，不为空则为更新
        //调用sql进行用户地址信息更新操作
        if (id == null){
            addressMapper.createNewBuyerAddress(buyerAddress);
        }else{
            addressMapper.updateByID(buyerAddress);
        }

    }
}
